package com.make.house.api.controller.admin;

import com.make.house.api.common.ECConstant;
import com.make.house.api.entity.user.ManagerUserEntity;
import com.make.house.api.model.ActionStatus;
import com.make.house.api.model.JSONResult;
import com.make.house.api.repository.user.ManagerUserRepository;
import com.make.house.api.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by yanglinlong on 18/8/22.
 * 管理员登录
 */

@RestController
@RequestMapping(ECConstant.API_REQUEST_BASE_URL + "/admin")
@Api("管理员登录")
public class AdminLoginController {

    @Autowired
    private ManagerUserRepository managerUserRepository;


    @ApiOperation(value="管理员登录", notes="管理员登录", response = AdminLoginResponseBean.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public JSONResult login(AdminLoginRequestParas paras){

        if (paras != null){

            if (StringUtils.isEmpty(paras.getName()) || StringUtils.isEmpty(paras.getPassword())){
                return JSONResult.newBuilder().setStatus(ActionStatus.PARAMAS_ERROR.inValue())
                        .setDesc("name and password must not be null").build();
            }

            ManagerUserEntity entity = managerUserRepository.findByUserNameAndPassword(paras.getName(), paras.getPassword());
            if (entity == null){
                return JSONResult.newBuilder().setStatus(ActionStatus.PARAMAS_ERROR.inValue())
                        .setDesc("name or password error").build();
            }
            entity.setLastLoginTime(System.currentTimeMillis());
            managerUserRepository.save(entity);
            AdminLoginResponseBean adminLoginResponseBean = new AdminLoginResponseBean();
            adminLoginResponseBean.adminName = entity.getUserName();
            adminLoginResponseBean.avatar = entity.getAvatar();
            return JSONResult.okResult(adminLoginResponseBean);
        }
        return JSONResult.NO_RESULT;

    }
}
